package com.cqsd.ioc.util;

import org.jetbrains.annotations.Contract;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author caseycheng
 * @date 2023/3/11-11:45
 **/
public final class AnnotationUtil {
    @Contract(pure = true)
    public static <A extends Annotation> A findAnnotation(Class<?> type, Class<A> anno) {
        return type.getAnnotation(anno);
    }

    /**
     * 在字段数组里获取被注释的字段
     *
     * @param fields
     * @param annotation
     * @return
     */
    @Contract(value = "!null,!null->!null", pure = true)
    public static List<Field> filterAnnotation(Field[] fields, Class<? extends Annotation> annotation) {
        return Arrays.stream(fields)
                .filter(field -> field.isAnnotationPresent(annotation))
                .collect(Collectors.toList());
    }

    /**
     * 在方法数组里获取被注释的方法
     *
     * @param methods
     * @param annotation
     * @return
     */
    @Contract(value = "!null,!null->!null", pure = true)
    public static List<Method> filterAnnotation(Method[] methods, Class<? extends Annotation> annotation) {
        return Arrays.stream(methods)
                .filter(method -> method.isAnnotationPresent(annotation))
                .collect(Collectors.toList());
    }

    /**
     * 在构造器数组中获取被注释的方法
     *
     * @param constructors
     * @param annotation
     * @return
     */
    @Contract(value = "!null,!null->!null", pure = true)
    public static List<Constructor<?>> filterAnnotation(Constructor<?>[] constructors, Class<? extends Annotation> annotation) {
        return Arrays.stream(constructors)
                .filter(constructor -> constructor.isAnnotationPresent(annotation))
                .collect(Collectors.toList());
    }

}
